from config.configs import GOAT_ERP_HOST, GOAT_ERP_PORT, DATA_PATH, ALPHA_DB_HOST, ALPHA_DB_PORT, LOCAL_HOST, \
    LOCAL_PORT, TRADE_URL
import pymongo
from tools.funciton import read_json_file
import os
import requests
import time
import json

korea = pymongo.MongoClient(GOAT_ERP_HOST, GOAT_ERP_PORT).goat_warehouse_korea
w1 = pymongo.MongoClient(GOAT_ERP_HOST, GOAT_ERP_PORT).goat_warehouse_w1
w2 = pymongo.MongoClient(GOAT_ERP_HOST, GOAT_ERP_PORT).goat_warehouse_w2
dev = pymongo.MongoClient(GOAT_ERP_HOST, GOAT_ERP_PORT).goat_warehouse_dev
jiwu = pymongo.MongoClient(ALPHA_DB_HOST, ALPHA_DB_PORT).jiwu
file = os.path.join(DATA_PATH, 'add_spu_datas.json')
trade = pymongo.MongoClient(TRADE_URL).tradingMarketSneaker



# def insert_spu_sku():
#     """新增货号尺码-韩国WMS（通过保税新系统数据）"""
#     spuId = read_json_file(file)['data']['commodityInfoList'][0]['showSpuId']
#     korea.spus.delete_many({'spuId': spuId})
#     korea.skus.delete_many({'spuId': spuId})
#     spu_datas = read_json_file(file)['data']['commodityInfoList'][0]
#     spu_param = {'spuId': spuId, 'title': spu_datas['title'], 'categoryName': spu_datas['categoryName'],
#                  'brandName': spu_datas['brandName'], 'brandId': spu_datas['brandId'],
#                  'categoryId': spu_datas['categoryId'],
#                  'articleNumber': spu_datas['articleNumber'], 'spuLogo': spu_datas['logoUrl'],
#                  'createdAt': int(round(time.time() * 1000)), 'updatedAt': int(round(time.time() * 1000))}
#     korea.spus.insert_one(spu_param)
#     sku_list = read_json_file(file)['data']['commodityInfoList'][0]['commodityItemInfoList']
#     for i in range(len(sku_list)):
#         # items = sku_list[i]['skuPropsList']
#         # sorted_items = sorted(items, key=lambda x: x['level'])
#         # new_dict = {item['name']: item['value'] for item in sorted_items}
#         # json_string = json.dumps(new_dict, ensure_ascii=False)
#         size = {"尺码": sku_list[i]['skuPropAllSpecification'][0]["skuProp"].split(' ')[2]}
#         sku_param = {"spuId": spuId, "skuId": sku_list[i]['showSkuId'], "properties": json.dumps(size, ensure_ascii=False).replace(' ',''), 'barcode': sku_list[i]['barCode'],
#                      'status': 1,
#                      "__v": 0, "createdAt": int(round(time.time() * 1000)), "updatedAt": int(round(time.time() * 1000))}
#         korea.skus.insert_one(sku_param)


def register_user(username, password):
    """新建用户"""
    url = "https://korea-api.hkmotivate.com/auth/register"
    payload = json.dumps({
        "mobile": username,
        "username": username,
        "password": password,
        "isAdmin": False
    })
    headers = {
        'Authorization': 'Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpZCI6IkRyZVVzZ29VWEUiLCJpc0FkbWluIjp0cnVlLCJpYXQiOjE3MTMzMTY4NzgsImV4cCI6MTcxMzkyMTY3OH0.5Sc5YL2_O_f6bbBEu8RfNKIqpjDv35x_qM7NFE0XgO4',
        'User-Agent': 'Apifox/1.0.0 (https://apifox.com)',
        'Content-Type': 'application/json',
        'token': 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpZCI6IkRyZVVzZ29VWEUiLCJpc0FkbWluIjp0cnVlLCJpYXQiOjE3MTMzMTY4NzgsImV4cCI6MTcxMzkyMTY3OH0.5Sc5YL2_O_f6bbBEu8RfNKIqpjDv35x_qM7NFE0XgO4',
        'Accept': '*/*',
        'Host': 'korea-api.hkmotivate.com',
        'Connection': 'keep-alive'
    }
    response = requests.request("POST", url, headers=headers, data=payload)
    print(response.json())


def korea_insert_spu_by_jiwu(articleNumber):
    """将集物的商品信息，插入到goat_warehouse_korea数据库中"""
    spu_data = jiwu.spus.find_one({"articleNumber": articleNumber})
    if spu_data is None:
        print("集物库中该商品不存在")
    else:
        spuId = spu_data['spuId']
        sku_data = [i for i in jiwu.skus.find({"spuId": spuId})]
        if korea.spus.find_one({"spuId": spuId}):
            print("该商品已存在")
        else:
            korea.spus.insert_one(spu_data)
            korea.skus.insert_many(sku_data)


def korea_insert_spu_api():
    """新增货号尺码-（直接通过得物api查询数据）"""
    res = read_json_file(file)['data']
    for i in range(len(read_json_file(file)['data'])):
        if '定制球鞋' in res[i]['title']:
            pass
        else:
            spuId = read_json_file(file)['data'][i]['spu_id']
            korea.spus.delete_one({'spuId': spuId})
            korea.skus.delete_many({'spuId': spuId})
            spu_datas = read_json_file(file)['data'][i]
            sku_datas = read_json_file(file)['data'][i]['skus']
            spu_param = {'spuId': spuId,
                         'title': spu_datas['title'],
                         'brandId': spu_datas['brand_id'],
                         'brandName': spu_datas['brand_name'],
                         'categoryId': spu_datas['category_id'],
                         'categoryName': spu_datas['category_name'],
                         'articleNumber': spu_datas['article_number'],
                         'otherNumbers': spu_datas['other_numbers'],
                         'spuLogo': spu_datas['spu_logo'],
                         'authPrice': spu_datas['auth_price'] / 100,
                         'supportCross': spu_datas['support_cross'],
                         'createdAt': int(round(time.time() * 1000)),
                         'updatedAt': int(round(time.time() * 1000)),
                         "status": 1}
            korea.spus.insert_one(spu_param)
            for z in range(len(sku_datas)):
                items = json.loads(sku_datas[z]['properties'])
                sku_param = {"spuId": spuId, "skuId": sku_datas[z]['sku_id'],
                             "properties": json.dumps(items, ensure_ascii=False).replace(" ", ""),
                             'barcode': sku_datas[z]['barcode'],
                             'status': 1,
                             "__v": 0, "createdAt": int(round(time.time() * 1000)),
                             "updatedAt": int(round(time.time() * 1000))}
                korea.skus.insert_one(sku_param)


def wms_insert_spu_sku_api():
    """新增货号尺码-（直接通过得物api查询数据）"""
    for i in range(len(read_json_file(file)['data'])):
        spuId = read_json_file(file)['data'][i]['spu_id']
        w1.spus.delete_one({'spuId': spuId})
        w1.skus.delete_many({'spuId': spuId})
        w2.spus.delete_one({'spuId': spuId})
        w2.skus.delete_many({'spuId': spuId})
        spu_datas = read_json_file(file)['data'][i]
        sku_datas = read_json_file(file)['data'][i]['skus']
        spu_param = {'spuId': spuId,
                     'title': spu_datas['title'],
                     'brandId': spu_datas['brand_id'],
                     'brandName': spu_datas['brand_name'],
                     'categoryId': spu_datas['category_id'],
                     'categoryName': spu_datas['category_name'],
                     'articleNumber': spu_datas['article_number'],
                     'otherNumbers': spu_datas['other_numbers'],
                     'spuLogo': spu_datas['spu_logo'],
                     'authPrice': spu_datas['auth_price'] / 100,
                     'supportCross': spu_datas['support_cross'],
                     'createdAt': int(round(time.time() * 1000)),
                     'updatedAt': int(round(time.time() * 1000)),
                     "status": 1}
        w1.spus.insert_one(spu_param)
        w2.spus.insert_one(spu_param)
        for z in range(len(sku_datas)):
            items = json.loads(sku_datas[z]['properties'])
            sku_param = {"spuId": spuId, "skuId": sku_datas[z]['sku_id'],
                         "properties": json.dumps(items, ensure_ascii=False).replace(" ", ""),
                         'barcode': sku_datas[z]['barcode'],
                         'status': 1,
                         "__v": 0, "createdAt": int(round(time.time() * 1000)),
                         "updatedAt": int(round(time.time() * 1000))}
            w1.skus.insert_one(sku_param)
            w2.skus.insert_one(sku_param)


def korea_insert_spu_sku_dewu(articleNumbers: list):
    """新增货号尺码-（直接通过得物api查询数据）"""
    s = 0
    for articleNumber in articleNumbers:
        url = f'http://139.224.198.98:3000/product/dewu/query/{articleNumber}'
        headers = {'x-internal-access': 'mI7lfclmb8tyCDhMgc1gTz6wZVKEQ82f'}
        response = requests.get(url, headers=headers)
        print(response.json())
        spu_data = response.json()['data']
        sku_data = spu_data['skus']
        for i in ['id', 'category','skus']:
            spu_data.pop(i)
        if spu_data is None:
            print(f"{articleNumber}:集物库中该商品不存在")
        else:
            spuId = spu_data['spuId']
            for j in ['id', 'size']:
                for k in range(len(sku_data)):
                    sku_data[k].pop(j)
            if korea.spus.find_one({"spuId": spuId}):
                korea.spus.delete_one({'spuId': spuId})
                korea.skus.delete_many({'spuId': spuId})
            else:
                korea.spus.insert_one(spu_data)
                print(f"{articleNumbers}插入成功")
                s += 1
                print(f"{s}个商品插入成功")
                korea.skus.insert_many(sku_data)



def trade_insert_spu_api():
    """新增货号尺码-（直接通过得物api查询数据）"""
    res = read_json_file(file)['data']
    for i in range(len(read_json_file(file)['data'])):
        if '定制球鞋' in res[i]['title']:
            pass
        else:
            spuId = read_json_file(file)['data'][i]['spu_id']
            trade.spus.delete_one({'spuId': spuId})
            trade.skus.delete_many({'spuId': spuId})
            spu_datas = read_json_file(file)['data'][i]
            sku_datas = read_json_file(file)['data'][i]['skus']
            spu_param = {'spuId': spuId,
                         'title': spu_datas['title'],
                         'brandId': spu_datas['brand_id'],
                         'brandName': spu_datas['brand_name'],
                         'categoryId': spu_datas['category_eid'],
                         'categoryName': spu_datas['category_name'],
                         'articleNumber': spu_datas['article_number'],
                         'otherNumbers': spu_datas['other_numbers'],
                         'spuLogo': spu_datas['spu_logo'],
                         'authPrice': spu_datas['auth_price'] / 100,
                         'supportCross': spu_datas['support_cross'],
                         'createdAt': int(round(time.time() * 1000)),
                         'updatedAt': int(round(time.time() * 1000)),
                         "status": 1}
            trade.spus.insert_one(spu_param)
            for z in range(len(sku_datas)):
                items = json.loads(sku_datas[z]['properties'])
                sku_param = {"spuId": spuId, "skuId": sku_datas[z]['sku_id'],
                             "properties": json.dumps(items, ensure_ascii=False).replace(" ", ""),
                             'barcode': sku_datas[z]['barcode'],
                             'status': 1,
                             "__v": 0, "createdAt": int(round(time.time() * 1000)),
                             "updatedAt": int(round(time.time() * 1000))}
                trade.skus.insert_one(sku_param)


# korea_insert_spu_sku_dewu(['HV8563-600'])
korea_insert_spu_api()
# wms_insert_spu_sku_api()
# trade_insert_spu_api()